package com.by.wx.servlet;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.by.wx.util.AuthUtil;
import com.by.wx.util.HttpClientManager;

import net.sf.json.JSONObject;
@Controller
@RequestMapping("/")
public class WXController {
	@RequestMapping("index")
	public String index(){
		System.out.println("index");
		return "index";
	}
	@RequestMapping("loginInit")
	public String loginInit(HttpServletRequest request,HttpServletResponse response) throws Exception  {
		    //回调地址,要跟下面的地址能调通(getWechatGZAccessToken.do)
		    String backUrl="https://h5.gzbaoya.cn/getWechatGZAccessToken.do";
//		    String backUrl="https://192.168.1.222/getWechatGZAccessToken.do";
		    System.out.println(backUrl);
		    /**
			*这儿一定要注意！！首尾不能有多的空格（因为直接复制往往会多出空格），其次就是参数的顺序不能变动
		    **/
		    String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AuthUtil.APPID+"&redirect_uri=" 
		    		+ URLEncoder.encode(backUrl,"UTF-8")
		    	   // &response_type=code    &scope=snsapi_userinfo                &#wechat_redirect'
		    		+"&response_type=code" +"&scope=snsapi_userinfo" +"&state=STATE#wechat_redirect";
		    System.out.println(url);
		    return "redirect:"+url;
	}
	@RequestMapping("getWechatGZAccessToken")
	public String getWechatGZAccessToken(HttpServletRequest request,HttpServletResponse response) throws Exception{
			//微信公众号的APPID和APPSECRET
			String code=request.getParameter("code");
	        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID+
	                "&secret=" +AuthUtil.APPSECRET+"&code=" +code+"&grant_type=authorization_code";
	        String result = HttpClientManager.getUrlData(url);
			Map<String,Object> data = JSONObject.fromObject(result);
	        String openid=data.get("openid").toString();
	        String token=data.get("access_token").toString();
	        //获取信息
	        String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token=" +token+
	                "&openid=" +openid+
	                "&lang=zh_CN";
	        String infoResult = HttpClientManager.getUrlData(infoUrl);
	        System.out.println("infoResult="+infoResult);
			return infoResult;
//	        String redirectUrl = "https://www.baidu.com";
//			return "success";
		}

}
